package com.apimanage.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;

/**
 * Spring Security配置类
 * 用于配置网关的安全策略，特别是允许访问/doc.html路径
 */
@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {

    /**
     * 配置安全过滤器链
     * 注意：因为我们使用的是Spring Cloud Gateway（基于WebFlux），所以需要使用ServerHttpSecurity
     */
    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        // 配置安全策略
        http
            // 禁用CSRF保护（API网关通常不需要）
            .csrf(csrf -> csrf.disable())
            // 配置授权规则
            .authorizeExchange(exchanges -> exchanges
                // 允许所有请求访问认证相关的路径
                .pathMatchers("/api/auth-center/auth/**", "/api/auth-center/call/**").permitAll()
                // 允许所有请求访问Swagger和Knife4j相关路径
                .pathMatchers("/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**", "/doc.html", "/webjars/**", "/swagger-resources/**").permitAll()
                // 其他所有请求都需要认证
                .anyExchange().authenticated()
            )
            // 禁用HTTP Basic认证
            .httpBasic(httpBasic -> httpBasic.disable())
            // 禁用表单登录
            .formLogin(formLogin -> formLogin.disable());
        
        return http.build();
    }
}